<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>单点拖动平行四边形</title>
<style>
  svg { border: 1px solid #ccc; background: #f9f9f9; display: block; margin: 20px auto; }
  polygon { fill: lightblue; stroke: black; stroke-width: 2; }
  circle { fill: red; cursor: pointer; }
  button { display: block; margin: 10px auto; padding: 5px 15px; font-size: 16px; }
</style>
</head>
<body>


<svg id="canvas" width="800" height="600">
  <!-- 两条平行线 -->
  <line x1="50" y1="200" x2="750" y2="200" stroke="black" stroke-width="2"/>
  <line x1="50" y1="450" x2="750" y2="450" stroke="black" stroke-width="2"/>

  <!-- 初始矩形 -->
  <polygon id="shape" points="250,200 550,200 550,450 250,450"/>

  <!-- 上边左顶点可拖动 -->
  <circle id="topLeft" class="drag" cx="250" cy="200" r="8"/>
</svg>

<button id="resetBtn">复原矩形</button>

<script>
const svg = document.getElementById('canvas');
const shape = document.getElementById('shape');
const topLeft = document.getElementById('topLeft');
const resetBtn = document.getElementById('resetBtn');
let selected = null;

// 初始矩形参数
const initialTopLeft = {x: 250, y: 200};
const initialTopRightX = 550;
const bottomLeft = {x: 250, y: 450};
const bottomRight = {x: 550, y: 450};
const rectHeight = bottomLeft.y - initialTopLeft.y;

topLeft.addEventListener('mousedown', e => selected = topLeft);

svg.addEventListener('mousemove', e => {
  if (!selected) return;

  let pt = svg.createSVGPoint();
  pt.x = e.clientX;
  pt.y = e.clientY;
  let cursorpt = pt.matrixTransform(svg.getScreenCTM().inverse());

  const topY = bottomLeft.y - rectHeight;
  cursorpt.y = topY;

  // 移动左顶点，右顶点同步保持平行四边形
  const dx = cursorpt.x - initialTopLeft.x;
  const newTopRightX = initialTopRightX + dx;

  topLeft.cx.baseVal.value = cursorpt.x;
  topLeft.cy.baseVal.value = topY;

  const points = [
    `${cursorpt.x},${topY}`,
    `${newTopRightX},${topY}`,
    `${bottomRight.x},${bottomRight.y}`,
    `${bottomLeft.x},${bottomLeft.y}`
  ].join(' ');
  shape.setAttribute('points', points);
});

// 鼠标抬起
window.addEventListener('mouseup', () => selected = null);

// 复原按钮点击事件
resetBtn.addEventListener('click', () => {
  // 恢复顶点位置
  topLeft.cx.baseVal.value = initialTopLeft.x;
  topLeft.cy.baseVal.value = initialTopLeft.y;

  // 恢复矩形
  const points = [
    `${initialTopLeft.x},${initialTopLeft.y}`,
    `${initialTopRightX},${initialTopLeft.y}`,
    `${bottomRight.x},${bottomRight.y}`,
    `${bottomLeft.x},${bottomLeft.y}`
  ].join(' ');
  shape.setAttribute('points', points);
});
</script>
</body>
</html>
